<?php

namespace backend\models\form;

use api\service\OrderService;
use backend\models\AdminUser;
use common\models\Order;
use common\service\BaseToolService;
use common\service\BusinessService;
use common\service\ConstatService;
use common\service\UserOrderCountServer;
use common\service\UtilService;
use yii\base\Model;
use Yii ;

class ChangeStatusForm extends Model {

    public $sender_name;
    public $sender_phone ;
    public $status;
    public $cancel_sub_status;
    public $exception_sub_status;
    public $reason ;


    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['status'],'required'],
            [['sender_name','sender_phone','cancel_sub_status','exception_sub_status','reason'], 'safe'],
            [['status'],'validStatus'],
            [['status','sender_phone','sender_name','cancel_sub_status','exception_sub_status','reason'], 'filter','filter'=>'\yii\helpers\HtmlPurifier::process']];
    }

    public function validStatus(){
        if(in_array($this->status,ConstatService::ORDER_STATUS)==false){
            $this->addError("status", "状态不合法") ;
            return false ;
        }
        if($this->status==ConstatService::ORDER_CANCEL){
            if(empty($this->cancel_sub_status)){
                $this->addError("sub_status", "请选择子状态") ;
                return false ;
            }
        }
        if($this->status==ConstatService::ORDER_EXCEPTION){
            if(empty($this->exception_sub_status)){
                $this->addError("sub_status", "请选择子状态") ;
                return false ;
            }
        }
    }


    public function attributeLabels() {
        return [
            'status' => '状态' ,
            'sender_name'=>'配送员',
            'sender_phone'=>'配送员电话',
            'cancel_sub_status'=>'子状态',
            'exception_sub_status'=>'子状态',
        ] ;
    }

    public  function changeStatus($orderno){
        if(empty($orderno)){
            return ["code"=>400,"msg"=>"订单号不能空"];
        }

        $order = Order::findOne(["orderno"=>$orderno]) ;

        if(empty($order)){
            return ["code"=>400,"msg"=>"不存在该订单"];
        }

        $oldStatus = $order['status'] ;

        $statusArr = ConstatService::ORDER_STATUS_DESC ;

        if(empty($statusArr[$this->status])){
            return ["code"=>400,"msg"=>"状态不合法"];
        }

        if(!empty(Yii::$app->admin->identity->store_code)){
            if(Yii::$app->admin->identity->store_code!=$order['store_code']){
                return ["code"=>400,"msg"=>"无法操作其它门店的数据"];
            }
        };

        if($this->status==$oldStatus){
            return ["code"=>400,"msg"=>"状态一致不用修改"];
        }

        $curData = date("Y-m-d H:i:s") ;

        $connection = Yii::$app->db->beginTransaction();
        try {
            if($this->status==ConstatService::ORDER_EXCEPTION){
                if($order->status==ConstatService::ORDER_DISTRIBUTION){
                    $connection->rollBack() ;
                    return ["code"=>400,"msg"=>"待取的订单，无法直接修改为异常"];
                }
            }

            //异常转正常单,需要把原来异常的统计去掉
            if($order->status==ConstatService::ORDER_EXCEPTION && !empty($order->sender_user_id)){
                $countRs = UserOrderCountServer::countOrder($order->sender_user_id,"exception_to_normal") ;
                if($countRs['code']!=200){
                    $connection->rollBack() ;
                    return ["code"=>400,"msg"=>"更新订单统计失败,原因:".$countRs['msg']];
                }

//            if($order->sub_status!=9){
//                $order->customer_expect_time = null ;
//            }
            }

            //取消转正常单,需要把原来异常的统计去掉
            if($order->status==ConstatService::ORDER_CANCEL && !empty($order->sender_user_id)){
                $countRs = UserOrderCountServer::countOrder($order->sender_user_id,"cancel_to_normal") ;
                if($countRs['code']!=200){
                    $connection->rollBack() ;
                    return ["code"=>400,"msg"=>"更新订单统计失败,原因:".$countRs['msg']];
                }
            }

            if($this->status==ConstatService::ORDER_DISTRIBUTION){
                $order->status = $this->status ;
                $order->sender_name = '' ;
                $order->sender_phone  =  '' ;
                $order->sender_user_id = null ;
                $order->receive_data_time = null ;
                $order->receive_entity_time = null ;
                $order->dispatching_time = null ;
                $order->cancel_time = null ;
                $order->exception_time = null ;
                $order->sign_time = null ;
                $order->cost = null ;
//            $order->sub_status = 0 ;
//            $order->sub_status_desc = null ;
                $rs = $order->save() ;
                if(empty($rs)){
                    $msg = current($order->getFirstErrors());
                    $connection->rollBack() ;
                    return ["code"=>400,"msg"=>"失败,原因:".$msg];
                }

                $logArr['orderno'] = $orderno;
                $logArr['status'] = $this->status;
                $logArr['remark'] = "后台修改状态,改为待取" ;
                BusinessService::addOrderlog($logArr) ;
                $backendLogArr['orderno'] = $orderno;
                $backendLogArr['old_status'] = $oldStatus;
                $backendLogArr['status'] = $this->status;
                BusinessService::addBackendOrderlog($backendLogArr);
                $connection->commit() ;
                return ["code"=>200,"msg"=>"成功"];
            }


            if($this->sender_phone){
                $sendUser = AdminUser::findOne(["phone"=>$this->sender_phone]) ;
                if(empty($sendUser)){
                    $connection->rollBack() ;
                    return ["code"=>400,"msg"=>"用户不存在"];
                }
                $typeId = $sendUser->type_id ;
                $canArr = [ConstatService::ROLE_HQ_STORE_MANAGER,ConstatService::ROLE_HQ_SENDER] ;
                if(in_array($typeId,$canArr)==false){
                    $connection->rollBack() ;
                    return ["code"=>400,"msg"=>"该手机号不是配送员或门店管理员"];
                }
            }

            if(empty($this->sender_phone)){
                $needSenderArr = [ConstatService::ORDER_RECEIVE_DATA,ConstatService::ORDER_RECEIVE_ENTITY,ConstatService::ORDER_DISPATCHING,ConstatService::ORDER_FINISH] ;
                if(in_array($this->status,$needSenderArr)){
                    $connection->rollBack() ;
                    return ["code"=>400,"msg"=>"该状态需要配送员,请指定配送员"];
                }
            }

            if($this->status==ConstatService::ORDER_RECEIVE_DATA){
                if($this->sender_phone){
//                $sendUser = AdminUser::findOne(["phone"=>$this->sender_phone]) ;
//                if(empty($sendUser)){
//                    return ["code"=>400,"msg"=>"用户不存在"];
//                }
                    $sender_phone = $this->sender_phone ;
                    $sender_name = $sendUser->username ;
                    $sender_user_id = $sendUser->user_id ;
                }else{
                    $sender_phone = $order->sender_phone ;
                    $sender_name = $order->sender_name ;
                    $sender_user_id = $order->sender_user_id ;
                }

                $order->status = $this->status ;
                $order->sender_name = $sender_name ;
                $order->sender_phone  =  $sender_phone ;
                $order->sender_user_id = $sender_user_id ;
                $order->receive_data_time = date("Y-m-d H:i:s") ;
                $order->receive_entity_time = null ;
                $order->dispatching_time = null ;
                $order->cancel_time = null ;
                $order->exception_time = null ;
                $order->sign_time = null ;
//            $order->sub_status = 0 ;
//            $order->sub_status_desc = null ;
                $rs = $order->save() ;
                if(empty($rs)){
                    $msg = current($order->getFirstErrors());
                    $connection->rollBack() ;
                    return ["code"=>400,"msg"=>"失败,原因:".$msg];
                }

                $logArr['orderno'] = $orderno;
                $logArr['status'] = $this->status;
                $logArr['remark'] = "后台修改状态,改为取单,配送员:{$sender_name},电话:{$sender_phone}" ;
                BusinessService::addOrderlog($logArr) ;
                $backendLogArr['orderno'] = $orderno;
                $backendLogArr['old_status'] = $oldStatus;
                $backendLogArr['status'] = $this->status;
                BusinessService::addBackendOrderlog($backendLogArr);
                $connection->commit() ;
                return ["code"=>200,"msg"=>"成功"];
            }

            if($this->status==ConstatService::ORDER_RECEIVE_ENTITY){
                $logisticsCode = UtilService::getSystemParamByKey("logistics_code",null);//物流商编码

                $hqData = [
                    "logisticsCode" => $logisticsCode ,
                    "orderNo" => $orderno ,
                    "status" => 10 ,
                    "operateTime" => $curData ,
                    "timestamp" => BaseToolService::getMillisecond(),
                ] ;
                $rs = OrderService::changeOrderStatus($hqData);
                if($rs['code']!=200){
                    $connection->rollBack() ;
                    return ["code"=>400,"msg"=>"调用接口失败,原因:".$rs['msg']." 状态码:".$rs['code']];
                }

                if($this->sender_phone){
//                $sendUser = AdminUser::findOne(["phone"=>$this->sender_phone]) ;
//                if(empty($sendUser)){
//                    return ["code"=>400,"msg"=>"用户不存在"];
//                }
                    $sender_phone = $this->sender_phone ;
                    $sender_name = $sendUser->username ;
                    $sender_user_id = $sendUser->user_id ;
                }else{
                    $sender_phone = $order->sender_phone ;
                    $sender_name = $order->sender_name ;
                    $sender_user_id = $order->sender_user_id ;
                }

                $order->status = $this->status ;
                $order->sender_name = $sender_name ;
                $order->sender_phone  =  $sender_phone ;
                $order->sender_user_id = $sender_user_id ;
                $order->receive_entity_time = $curData ;
                $order->dispatching_time = null ;
                $order->cancel_time = null ;
                $order->exception_time = null ;
                $order->sign_time = null ;
//            $order->sub_status = 0 ;
//            $order->sub_status_desc = null ;
                $rs = $order->save() ;
                if(empty($rs)){
                    $msg = current($order->getFirstErrors());
                    $connection->rollBack() ;
                    return ["code"=>400,"msg"=>"失败,原因:".$msg];
                }

                $logArr['orderno'] = $orderno;
                $logArr['status'] = $this->status;
                $logArr['remark'] = "后台修改状态,改为取货,配送员:{$sender_name},电话:{$sender_phone}" ;
                BusinessService::addOrderlog($logArr) ;
                $backendLogArr['orderno'] = $orderno;
                $backendLogArr['old_status'] = $oldStatus;
                $backendLogArr['status'] = $this->status;
                BusinessService::addBackendOrderlog($backendLogArr);
                $connection->commit() ;
                return ["code"=>200,"msg"=>"成功"];
            }

            if($this->status==ConstatService::ORDER_DISPATCHING){
                if($this->sender_phone){
//                $sendUser = AdminUser::findOne(["phone"=>$this->sender_phone]) ;
//                if(empty($sendUser)){
//                    return ["code"=>400,"msg"=>"用户不存在"];
//                }
                    $sender_phone = $this->sender_phone ;
                    $sender_name = $sendUser->username ;
                    $sender_user_id = $sendUser->user_id ;
                }else{
                    $sender_phone = $order->sender_phone ;
                    $sender_name = $order->sender_name ;
                    $sender_user_id = $order->sender_user_id ;
                }

                $logisticsCode = UtilService::getSystemParamByKey("logistics_code",null);//物流商编码


                $hqData = [
                    "logisticsCode" => $logisticsCode ,
                    "orderNo" => $orderno ,
                    "status" => 11 ,
                    "operateTime" => $curData ,
                    "deliveryManName" => $sender_name ,
                    "deliveryManPhone" => $sender_phone ,
                    "timestamp" => BaseToolService::getMillisecond(),
                ] ;
                $rs = OrderService::changeOrderStatus($hqData);
                if($rs['code']!=200){
                    $connection->rollBack() ;
                    return ["code"=>400,"msg"=>"调用接口失败,原因:".$rs['msg']." 状态码:".$rs['code']];
                }

                $order->status = $this->status ;
                $order->sender_name = $sender_name ;
                $order->sender_phone  =  $sender_phone ;
                $order->sender_user_id = $sender_user_id ;
                $order->dispatching_time = $curData ;
                $order->cancel_time = null ;
                $order->exception_time = null ;
                $order->sign_time = null ;
//            $order->sub_status = 0 ;
//            $order->sub_status_desc = null ;
                $rs = $order->save() ;
                if(empty($rs)){
                    $msg = current($order->getFirstErrors());
                    $connection->rollBack() ;
                    return ["code"=>400,"msg"=>"失败,原因:".$msg];
                }

                $logArr['orderno'] = $orderno;
                $logArr['status'] = $this->status;
                $logArr['remark'] = "后台修改状态,改为配送,配送员:{$sender_name},电话:{$sender_phone}" ;
                BusinessService::addOrderlog($logArr) ;
                $backendLogArr['orderno'] = $orderno;
                $backendLogArr['old_status'] = $oldStatus;
                $backendLogArr['status'] = $this->status;
                BusinessService::addBackendOrderlog($backendLogArr);
                $connection->commit() ;
                return ["code"=>200,"msg"=>"成功"];
            }

            if($this->status==ConstatService::ORDER_FINISH){
                $logisticsCode = UtilService::getSystemParamByKey("logistics_code",null);//物流商编码

                $hqData = [
                    "logisticsCode" => $logisticsCode ,
                    "orderNo" => $orderno ,
                    "status" => 20 ,
                    "operateTime" => $curData ,
                    "timestamp" => BaseToolService::getMillisecond(),
                ] ;
                $rs = OrderService::changeOrderStatus($hqData);
                if($rs['code']!=200){
                    $connection->rollBack() ;
                    return ["code"=>400,"msg"=>"调用接口失败,原因:".$rs['msg']." 状态码:".$rs['code']];
                }

                if($this->sender_phone){
                    $sendUser = AdminUser::findOne(["phone"=>$this->sender_phone]) ;
                    if(empty($sendUser)){
                        $connection->rollBack() ;
                        return ["code"=>400,"msg"=>"用户不存在"];
                    }
                    $sender_phone = $this->sender_phone ;
                    $sender_name = $sendUser->username ;
                    $sender_user_id = $sendUser->user_id ;
                }else{
                    $sender_phone = $order->sender_phone ;
                    $sender_name = $order->sender_name ;
                    $sender_user_id = $order->sender_user_id ;
                }

                if(!empty($order->sub_status) && $order->sub_status==9 && !empty($order->customer_expect_time)){
                    if(strtotime('now')>strtotime($order->customer_expect_time)){
                        $isOnTime = 2 ;
                    }else{
                        $isOnTime = 1 ;
                    }
                }else{
                    if(strtotime('now')>strtotime($order->expect_time)){
                        $isOnTime = 2 ;
                    }else{
                        $isOnTime = 1 ;
                    }
                }

                //计算价格
                $cost = BusinessService::calculationCost($order->weight,$order->business_type);

                $order->status = $this->status ;
                $order->sender_name = $sender_name ;
                $order->sender_phone  =  $sender_phone ;
                $order->sender_user_id = $sender_user_id ;
                $order->cancel_time = null ;
                $order->exception_time = null ;
                $order->sign_time = $curData ;
                $order->is_on_time = $isOnTime ;
                $order->cost = $cost ;
//            $order->sub_status = 0 ;
//            $order->sub_status_desc = null ;
                $rs = $order->save() ;
                if(empty($rs)){
                    $msg = current($order->getFirstErrors());
                    $connection->rollBack() ;
                    return ["code"=>400,"msg"=>"失败,原因:".$msg];
                }

                $countRs = UserOrderCountServer::countOrder($order->sender_user_id,"sign",$isOnTime) ;

                $logArr['orderno'] = $orderno;
                $logArr['status'] = $this->status;
                $logArr['remark'] = "后台修改状态,改为妥投,配送员:{$sender_name},电话:{$sender_phone}" ;
                BusinessService::addOrderlog($logArr) ;
                $backendLogArr['orderno'] = $orderno;
                $backendLogArr['old_status'] = $oldStatus;
                $backendLogArr['status'] = $this->status;
                BusinessService::addBackendOrderlog($backendLogArr);
                $connection->commit() ;
                return ["code"=>200,"msg"=>"成功"];
            }

            if($this->status==ConstatService::ORDER_EXCEPTION){
                $logisticsCode = UtilService::getSystemParamByKey("logistics_code",null);//物流商编码

                $hqData = [
                    "logisticsCode" => $logisticsCode ,
                    "orderNo" => $orderno ,
                    "status" => 12 ,
                    "operateTime" => $curData ,
                    "timestamp" => BaseToolService::getMillisecond(),
                ] ;
                $rs = OrderService::changeOrderStatus($hqData);
                if($rs['code']!=200){
                    $connection->rollBack() ;
                    return ["code"=>400,"msg"=>"调用接口失败,原因:".$rs['msg']." 状态码:".$rs['code']];
                }

                $exceptionDescArr = ConstatService::ORDER_EXCEPTION_SUB_STATUS_DESC ;
                $sub_status_desc = empty($exceptionDescArr[$this->exception_sub_status])?"":$exceptionDescArr[$this->exception_sub_status];
                if($this->exception_sub_status==99){
                    $sub_status_desc = $this->reason ;
                }

                if($this->sender_phone){
                    $sender_phone = $this->sender_phone ;
                    $sender_name = $sendUser->username ;
                    $sender_user_id = $sendUser->user_id ;
                }else{
                    $sender_phone = $order->sender_phone ;
                    $sender_name = $order->sender_name ;
                    $sender_user_id = $order->sender_user_id ;
                }

                $order->sender_name = $sender_name ;
                $order->sender_phone  =  $sender_phone ;
                $order->sender_user_id = $sender_user_id ;
                $order->status = $this->status ;
                $order->exception_time = $curData ;
                $order->sub_status = empty($this->exception_sub_status)?$order->sub_status:$this->exception_sub_status ;
                $order->sub_status_desc = empty($sub_status_desc)?$order->sub_status_desc:$sub_status_desc ;
                $order->old_status = $oldStatus ;
                $rs = $order->save() ;
                if(empty($rs)){
                    $msg = current($order->getFirstErrors());
                    $connection->rollBack() ;
                    return ["code"=>400,"msg"=>"失败,原因:".$msg];
                }

                $countRs = UserOrderCountServer::countOrder($order->sender_user_id,"exception") ;

                $logArr['orderno'] = $orderno;
                $logArr['status'] = $this->status;
                $logArr['sub_status'] = $order->sub_status;
                $logArr['remark'] = "后台修改状态,改为异常,原因:{$order->sub_status_desc}" ;
                BusinessService::addOrderlog($logArr) ;
                $backendLogArr['orderno'] = $orderno;
                $backendLogArr['old_status'] = $oldStatus;
                $backendLogArr['status'] = $this->status;
                BusinessService::addBackendOrderlog($backendLogArr);
                $connection->commit() ;
                return ["code"=>200,"msg"=>"成功"];
            }

            if($this->status==ConstatService::ORDER_CANCEL){
                $logisticsCode = UtilService::getSystemParamByKey("logistics_code",null);//物流商编码

                $hqData = [
                    "logisticsCode" => $logisticsCode ,
                    "orderNo" => $orderno,
                    "status" => 30 ,
                    "operateTime" => $curData ,
                    "timestamp" => BaseToolService::getMillisecond(),
                ] ;
                $rs = OrderService::changeOrderStatus($hqData);
                if($rs['code']!=200){
                    $connection->rollBack() ;
                    return ["code"=>400,"msg"=>"调用接口失败,原因:".$rs['msg']." 状态码:".$rs['code']];
                }

                if($this->sender_phone){
                    $sender_phone = $this->sender_phone ;
                    $sender_name = $sendUser->username ;
                    $sender_user_id = $sendUser->user_id ;
                }else{
                    $sender_phone = $order->sender_phone ;
                    $sender_name = $order->sender_name ;
                    $sender_user_id = $order->sender_user_id ;
                }

                $order->sender_name = $sender_name ;
                $order->sender_phone  =  $sender_phone ;
                $order->sender_user_id = $sender_user_id ;

                $cancelDescArr = ConstatService::ORDER_CANCEL_SUB_STATUS_DESC ;
                $sub_status_desc = empty($cancelDescArr[$this->cancel_sub_status])?"":$cancelDescArr[$this->cancel_sub_status];
                if($this->cancel_sub_status==99){
                    $sub_status_desc = $this->reason ;
                }

                $order->status = $this->status ;
                $order->cancel_time = $curData ;
                $order->sub_status = empty($this->cancel_sub_status)?$order->sub_status:$this->cancel_sub_status ;
                $order->sub_status_desc = empty($sub_status_desc)?$order->sub_status_desc:$sub_status_desc ;
                $rs = $order->save() ;
                if(empty($rs)){
                    $msg = current($order->getFirstErrors());
                    $connection->rollBack() ;
                    return ["code"=>400,"msg"=>"失败,原因:".$msg];
                }

                $countRs = UserOrderCountServer::countOrder($order->sender_user_id,"cancel") ;

                $logArr['orderno'] = $orderno;
                $logArr['status'] = $this->status;
                $logArr['sub_status'] = $order->sub_status;
                $logArr['remark'] = "后台修改状态,改为取消,原因:{$order->sub_status_desc}" ;
                BusinessService::addOrderlog($logArr) ;
                $backendLogArr['orderno'] = $orderno;
                $backendLogArr['old_status'] = $oldStatus;
                $backendLogArr['status'] = $this->status;
                BusinessService::addBackendOrderlog($backendLogArr);

                $connection->commit() ;
                return ["code"=>200,"msg"=>"成功"];
            }
        }catch (\Exception $e){
            $connection->rollBack();
            BaseToolService::error($e,"ChangeStatusForm_changeStatus_error") ;
            return ["code"=>400,"msg"=>"异常:".$e->getMessage()];
        }

    }



}
